﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using DevelopTool.Bll.LocalDbBlls;
using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using DevelopTool.Forms.CommonForms;
using DevelopTool.Forms.CommonHelpers;
using Sunny.UI;

namespace DevelopTool.Forms.SafetyForms
{
    /// <summary>
    /// 登录窗体
    /// </summary>
    public partial class LogingForm : BaseUIForm
    {
        /// <summary>
        /// 确认标志
        /// </summary>
        public bool IsConfirm { get; set; } = false;

        private LocalUserBll localUserBll;

        /// <summary>
        /// 拥有此窗体的父窗体
        /// </summary>
        private UIForm ownerForm;

        /// <summary>
        /// 新用户窗口
        /// </summary>
        private NewUserForm newUserForm;

        /// <summary>
        /// 是否手动打开登录窗口，例如：切换用户
        /// </summary>
        private bool isManualStart;

        public LogingForm(UIForm ownerForm,bool isManualStart)
        {
            InitializeComponent();
            this.ownerForm = ownerForm;
            this.isManualStart = isManualStart;
        }

        private void LogingForm_Load(object sender,EventArgs e)
        {
            localUserBll = new LocalUserBll();

            //默认数据库路径
            string defaultDbPath = Setting.System.DbFilePath;
            if(File.Exists(defaultDbPath))
            {
                textDbPath.Text = defaultDbPath;
            }

            uiToolTip.SetToolTip(btnLoging,"奔跑吧少年~");
            uiToolTip.SetToolTip(btnNewUser,"新同学吗~");

            this.Activate();
            textPassword.Focus();

            this.ControlBoxFillHoverColor = this.ownerForm.ControlBoxFillHoverColor;

            this.cboAutoLoging.Checked = Setting.System.AutoLoging;

            ThemHelper.SetSystemThem(this);
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLoging_Click(object sender,EventArgs e)
        {
            Loging(false);
        }

        private void Loging(bool autoLoging)
        {
            if(!base.CheckData(this.textDbPath,"请选择数据库"))
            {
                this.textDbPath.Focus();
                return;
            }

            if(!File.Exists(this.textDbPath.Text))
            {
                this.ShowWarningNotifier("未识别到数据库文件，请检查路径是否正确");
                return;
            }

            if(!base.CheckData(this.textPassword,"请输入密码"))
            {
                this.textPassword.Focus();
                return;
            }

            var tuple = localUserBll.Loging(this.textDbPath.Text,textPassword.Text);//登录逻辑

            if(tuple.Item1 == 1)
            {
                //登录成功后，如果选择自动登录，那么保存密码到一个安全隐蔽的地方~
                if(Setting.System.AutoLoging) localUserBll.SavePassword(this.textPassword.Text);

                IsConfirm = true;
            }
            else if(tuple.Item1 == 0)
            {
                this.ShowErrorNotifier(tuple.Item2);
            }
            else
            {
                this.ShowErrorDialog(tuple.Item2);
            }
        }


        private void textPassword_TextChanged(object sender,EventArgs e)
        {
            base.TextBoxTextChanged(sender,e);
        }


        /// <summary>
        /// 新用户按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNewUser_Click(object sender,EventArgs e)
        {
            newUserForm = new NewUserForm(this.ownerForm);
            newUserForm.Show(this.ownerForm);
            WaitNewUser();
            this.Hide();
        }


        /// <summary>
        /// 等待新用户创建完成
        /// </summary>
        private void WaitNewUser()
        {
            Timer timer = new Timer
            {
                Interval = 1000,
                Enabled = true
            };
            timer.Tick += delegate (object sender,EventArgs e)
            {
                if(newUserForm.IsConfirm == 1)
                {
                    timer.Stop();
                    newUserForm.Close();

                    IsConfirm = true;
                }
                else if(newUserForm.IsConfirm == 2)
                {
                    timer.Stop();
                    newUserForm.Close();
                    this.Show();
                }
            };
        }


        /// <summary>
        /// 选择数据库文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textDbPath_ButtonClick(object sender,EventArgs e)
        {
            using(OpenFileDialog dialog = new OpenFileDialog { Title = "选择数据库文件" })
            {
                if(File.Exists(Setting.System.DbFilePath)) dialog.InitialDirectory = Path.GetDirectoryName(Setting.System.DbFilePath);
                else dialog.InitialDirectory = GlobalData.AppDirectory;

                dialog.Filter = $"{GlobalData.AppName_en}|*{GlobalData.AppDbFileExtension}";
                dialog.Multiselect = false;

                if(dialog.ShowDialog() == DialogResult.OK)
                {
                    textDbPath.Text = dialog.FileName;
                }
            }
        }

        /// <summary>
        /// 自动登录选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboAutoLoging_MouseClick(object sender,MouseEventArgs e)
        {
            if(this.cboAutoLoging.Checked)
            {
                CountDownAskMessageForm countDownAskMessageForm = new CountDownAskMessageForm($"{GlobalData.AppName_zh}-隐私安全风险，冷静期","开启此功能后可能有泄露隐私的风险，请在信任的环境中启用此功能！",5);

                if(countDownAskMessageForm.ShowDialog() != DialogResult.OK)
                {
                    this.cboAutoLoging.Checked = false;
                }
            }

            Setting.System.AutoLoging = this.cboAutoLoging.Checked;
        }

        private void LogingForm_VisibleChanged(object sender,EventArgs e)
        {
            if(this.Visible)
            {
                //绑定动画
                AnimatorHelper.BindShowAnimator(new List<Control>() {
                    { this.btnLoging},
                });

                this.Activate();
                textPassword.Focus();
            }
        }

        private void LogingForm_FormClosed(object sender,FormClosedEventArgs e)
        {
            if(!IsConfirm)
                base.ExitApp();
        }

        private void LogingForm_ExtendBoxClick(object sender,EventArgs e)
        {
            AboutHelper.ShowAbout();
        }
    }
}
